const express = require("express");
const Template = require("../model/template");
const router = express.Router();

router.get("/template", async (req, res) => {
    try {
        const temps = await Template.find({}).sort({ update_at: -1 });
        res.$success(temps);
    } catch (error) {
        res.$error(error);
    }
});

router.get("/template/:id", async (req, res) => {
    try {
        const temp = await Template.findById({ _id: req.params.id });
        if (temp) {
            res.$success(temp);

        } else {
            res.$success({}, 400);
        }
    } catch (error) {
        res.$error(error);
    }
});

router.post("/template", async (req, res) => {
    try {
        // console.log(11111111111111, req);
        const temps = await Template.create(req.body);
        res.$success(temps);
    } catch (error) {
        res.$error(error);
    }
});

router.put("/template/:id", async (req, res) => {
    try {
        const temp = await Template.updateMany({ _id: req.params.id }, {"$set": req.body}, { upsert: true });
        if (temp) {
            res.$success(temp);
        }else {
            res.$error("更新失败", 400);
        }
    } catch (error) {
        res.$error(error)
    }
})

router.delete("/template", async (req, res) => {
    try {
        const temps = await Template.deleteMany(req.body);
        res.$success("删除成功");
    } catch (error) {
        res.$error(error);
    }
});

module.exports = router;